package com.example.demo.controller.handler;

import com.example.demo.core.Result;
import com.example.demo.core.SystemCode;
import com.example.demo.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理器
 *
 * @author 叮当猫的百宝箱
 * @since 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public Result<Void> handleServiceException(ServiceException exception) {
        log.debug(
                "出现业务异常，业务错误码={}，描述文本={}",
                exception.getResultStatus().getCode(),
                exception.getMessage()
        );
        return Result.error(exception.getResultStatus(), exception.getMessage());
    }

    /**
     * 处理绑定异常（通过Validation框架验证请求参数时的异常）
     *
     * @param exception 抛出的异常
     * @return API全局响应对象
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException exception) {
        FieldError fieldError = exception.getBindingResult().getFieldError();
        String errorMessage = fieldError != null ? fieldError.getDefaultMessage() : "Unknown error occurred";
        return Result.error(SystemCode.ERROR_BAD_REQUEST, errorMessage);
    }

    /**
     * 未授权异常
     *
     * @param accessDeniedException 抛出的异常
     * @return API全局响应对象
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result<Void> handleAccessDeniedException(AccessDeniedException accessDeniedException) {
        return Result.error(SystemCode.ERROR_FORBIDDEN, "未授权");
    }

    /**
     * 处理系统（其它）异常
     *
     * @param throwable 抛出的异常
     * @return API全局响应对象
     */
    @ExceptionHandler(Throwable.class)
    public Result<Void> handleSystemError(Throwable throwable) {
        log.debug(
                "出现系统异常，异常类型={}，描述文本={}",
                throwable.getClass().getName(),
                throwable.getMessage()
        );
        throwable.printStackTrace();
        return Result.error(SystemCode.ERROR_UNKNOWN, throwable.getMessage());
    }
}
